package org.penguin.boot.security.controller;

import org.penguin.boot.security.dao.RoleRepository;
import org.penguin.boot.security.dto.UserDto;
import org.penguin.boot.security.entity.Role;
import org.penguin.boot.security.entity.User;
import org.penguin.boot.security.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private RoleRepository roleRepository;

    @Resource
    private UserService userService;

    /**
     * 分组校验
     *
     * @param registrar 注册用户基础信息封装类
     * @return
     */
    @PostMapping("/signup")
    public @ResponseBody User signup(@RequestBody @Validated UserDto registrar) {
        Optional<Role> optionalRole = roleRepository.findByName("ROLE_USER");
        if (optionalRole.isEmpty()) {
            return null;
        }
        User user = new User();
        user.setEmail(registrar.getEmail());
        user.setNickName(registrar.getNickName());
        user.setRoles(Collections.singletonList(optionalRole.get()));
        user.setPassword(registrar.getPassword());
        return userService.createUser(user);
    }


    @RequestMapping("/home")
    public String toHomePage(Model model) {
        List<User> userList = userService.findAll();
        model.addAttribute("userList", userList);
        return "/user/home";
    }
}
